import React, {PureComponent} from 'react';
import * as api from './api';
import styles from './style.css';
import PropTypes from 'prop-types';
import {
    PAGE,
    TABLE,
    DATETIME_FORMAT,
    FIXED_COLUMN_WIDTH,
    PAGINATION_OPTIONS,
    COMMON_TABLE_EMPTY_TEXT,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {injectIntl, formatMessage} from './intl';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {conventSorter, ListTypeCL, hasPermissions} from './utils';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {Table, Card, Affix, Alert, Row, Col, message} from 'antd';
import {purchaseSaleInventoryOrderStatus, saleOrderBusinessType} from '../Enum';
export class TablePanel extends PureComponent {
    state = {
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
    };
    static getDerivedStateFromProps(props, state) {
        if(props.data !== state.prevData)
            return {
                prevData: props.data,
                selectedRowKeys: [],
                selectedRows: []
            };
        return null;
    }
    affixOnChange = () => this.forceUpdate();
    // eslint-disable-next-line react/sort-comp
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    onEndBatchSubmit = type => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
        if(type === 'batchEffective')
            this.props.onEndBatchSXSubmit();
        else if(type === 'batchAbandon')
            this.props.onEndBatchZFSubmit();
        else
            this.props.onEndBatchGDSubmit();
    }
    onClickBatch = type => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            message.warning(formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的单据'
            }));
        else {
            this.setState({loading: true});
            if(type === 'batchEffective')
                api.batchEffective({details: this.state.selectedRows.map(v => ({
                    id: v.id,
                    rowVersion: v.rowVersion
                }))}).then(() => {
                    this.setState({loading: false});
                    this.props.querySearch();
                    this.props.onEndBatchSXSubmit();
                });
            else if(type === 'batchAbandon')
                api.batchAbandon({details: this.state.selectedRows.map(v => ({
                    id: v.id,
                    rowVersion: v.rowVersion
                }))}).then(() => {
                    this.setState({loading: false});
                    this.props.querySearch();
                    this.props.onEndBatchZFSubmit();
                });
            else
                api.batchSalePlanOrder({details: this.state.selectedRows.map(v => ({
                    id: v.id,
                    rowVersion: v.rowVersion
                }))}).then(() => {
                    this.setState({loading: false});
                    this.props.querySearch();
                    this.props.onEndBatchGDSubmit();
                });
        }
    }
    handlemenus = (r, key) => {
        this.setState({loading: true});
        if(key === 'abandon')
            api.batchAbandon({details: [{
                id: r.id,
                rowVersion: r.rowVersion
            }]}).then(() => {
                this.setState({loading: false});
                this.props.querySearch();
                this.onEndBatchSubmit('batchAbandon');
            });
        else if(key === 'takeEffect')
            api.batchEffective({details: [{
                id: r.id,
                rowVersion: r.rowVersion
            }]}).then(() => {
                this.setState({loading: false});
                this.props.querySearch();
                this.onEndBatchSubmit('batchEffective');
            });
        else
            api.batchSalePlanOrder({details: [{
                id: r.id,
                rowVersion: r.rowVersion
            }]}).then(() => {
                this.setState({loading: false});
                this.props.querySearch();
                this.onEndBatchSubmit('batchSalePlanOrder');
            });
    };
    render() {
        const {pageIndex, pageSize, total, initEnumData, permissions,
            isShowBatchSXPanel, isShowBatchZFPanel, isShowBatchGDPanel} = this.props;
        const sxMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <WrappedPopconfirm
                    key="batchEffective"
                    placement="topRight"
                    onConfirm={() => this.onClickBatch('batchEffective')}
                    id="batchEffective"
                    title={formatMessage({
                        id: 'tablePanel.message.batchEffective',
                        defaultMessage: '是否确认批量生效？'
                    })}>
                    <a className={styles.panelalertMessage}>{formatMessage({
                        id: 'tablePanel.operation.batchEffective',
                        defaultMessage: '批量生效'
                    })}</a>
                </WrappedPopconfirm>
            </Col>
        </Row>);
        const zfMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <WrappedPopconfirm
                    key="batchAbandon"
                    placement="topRight"
                    onConfirm={() => this.onClickBatch('batchAbandon')}
                    id="batchAbandon"
                    title={formatMessage({
                        id: 'tablePanel.message.batchAbandon',
                        defaultMessage: '是否确认批量作废？'
                    })}>
                    <a className={styles.panelalertMessage}>{formatMessage({
                        id: 'tablePanel.operation.batchAbandon',
                        defaultMessage: '批量作废'
                    })}</a>
                </WrappedPopconfirm>
            </Col>
        </Row>);
        const gdMessage = (<Row>
            <Col span={18}>{
                formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <WrappedPopconfirm
                    key="batchSalePlanOrder"
                    placement="topRight"
                    onConfirm={() => this.onClickBatch('batchSalePlanOrder')}
                    id="batchSalePlanOrder"
                    title={formatMessage({
                        id: 'tablePanel.message.batchSalePlanOrder',
                        defaultMessage: '是否确认批量生成滚动计划？'
                    })}>
                    <a className={styles.panelalertMessage}>{formatMessage({
                        id: 'tablePanel.operation.batchSalePlanOrder',
                        defaultMessage: '批量生成滚动计划'
                    })}</a>
                </WrappedPopconfirm>
            </Col>
        </Row>);
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.marketDepartmentCode',
                defaultMessage: '大区'
            }),
            dataIndex: 'marketDepartmentName',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.country',
                defaultMessage: '国家'
            }),
            dataIndex: 'country',
            sorter: true,
            render: (text, record) => <Link to={routes.detail.format(record.id, record)} >{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'dealerName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.submitYear',
                defaultMessage: '提报年份'
            }),
            dataIndex: 'submitYear',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.submitMonth',
                defaultMessage: '提报月份'
            }),
            dataIndex: 'submitMonth',
            sorter: true
        }, {
            title: formatMessage({
                id: 'tablePanel.column.businessType',
                defaultMessage: '业务类型'
            }),
            dataIndex: 'businessType',
            render: text => conventEnumValueToString(saleOrderBusinessType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partShipmentStatus',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(purchaseSaleInventoryOrderStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    // {
                    //     id: PERMISSION.takeEffect,
                    //     children: ref =>
                    //         <WrappedPopconfirm
                    //             id={r.id}
                    //             key="takeEffect"
                    //             title={formatMessage({
                    //                 id: 'tablePanel.popconfirm.message',
                    //                 defaultMessage: '是否继续?'
                    //             })}
                    //             onVisibleChange={ref.setMenuVisible}
                    //             onConfirm={() => this.handlemenus(r, 'takeEffect')}>
                    //             <a key="takeEffect">
                    //                 {formatMessage({
                    //                     id: 'tablePanel.operation.takeEffect',
                    //                     defaultMessage: '生效'
                    //                 })}
                    //             </a>
                    //         </WrappedPopconfirm>,
                    //     hidden: !(hasPermissions(permissions, PERMISSION.takeEffect) && hasPermissions(r.options, PERMISSION.takeEffect))
                    // },
                    {
                        id: PERMISSION.abandon,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="abandon"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={() => this.handlemenus(r, 'abandon')}>
                                <a key="abandon">
                                    {formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                    },
                    {
                        id: PERMISSION.salePlanOrder,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="salePlanOrder"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={() => this.handlemenus(r, 'salePlanOrder')}>
                                <a key="salePlanOrder">
                                    {formatMessage({
                                        id: 'tablePanel.operation.salePlanOrder',
                                        defaultMessage: '生成滚动计划'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.salePlanOrder) && hasPermissions(r.options, PERMISSION.salePlanOrder))
                    }
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        if(initEnumData.brands && initEnumData.brands.length > 1)
            columns.unshift({
                title: formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
            });
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = (isShowBatchSXPanel || isShowBatchZFPanel || isShowBatchGDPanel) ? {
            fixed: true,
            type: 'checkbox',
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            getCheckboxProps: record => ({
                disabled: record.status !== 1
            }),
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (keys, rows) => this.setState({
                selectedRowKeys: keys,
                selectedRows: rows
            })
        } : undefined;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Card>
                {isShowBatchSXPanel && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={sxMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={() => this.onEndBatchSubmit('batchEffective')} />
                </Affix>}
                {isShowBatchZFPanel && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={zfMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={() => this.onEndBatchSubmit('batchAbandon')} />
                </Affix>}
                {isShowBatchGDPanel && <Affix offsetTop={0} className={styles.alertMargin} onChange={this.affixOnChange}>
                    <Alert message={gdMessage} type="warning" closable showIcon
                        closeText={<span className={styles.closeText}>{formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={() => this.onEndBatchSubmit('batchSalePlanOrder')} />
                </Affix>}
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    rowSelection={rowSelection}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onEndBatchGDSubmit: PropTypes.func.isRequired,
    onEndBatchSXSubmit: PropTypes.func.isRequired,
    onEndBatchZFSubmit: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import * as actions from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? ListTypeCL(initData.brands) : [];
        return {
            brands, // 品牌
            initData
        };
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    permissions: getPermissions(state),
    initEnumData: getinitEnumData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    isShowBatchSXPanel: state.getIn(['page', 'ui', 'showBatchSXPanel']),
    isShowBatchZFPanel: state.getIn(['page', 'ui', 'showBatchZFPanel']),
    isShowBatchGDPanel: state.getIn(['page', 'ui', 'showBatchGDPanel']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex'])
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            actions.tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            actions.tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    querySearch: () => dispatch(actions.querySearch()),
    onChangeSort: option => dispatch(actions.tableSearch(option)),
    onEndBatchSXSubmit: () => dispatch(actions.clearBatchSX()),
    onEndBatchZFSubmit: () => dispatch(actions.clearBatchZF()),
    onEndBatchGDSubmit: () => dispatch(actions.clearBatchGD()),
});
import {connect} from 'react-redux';
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
